package com.krain.ddbb.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import com.krain.ddbb.R;
import com.krain.ddbb.adapter.MultipleAlbumAdpter;
import com.krain.ddbb.base.BaseActivity;
import com.krain.ddbb.constant.Keys;
import com.krain.corelibrary.helper.ImageHelper;
import com.krain.corelibrary.helper.imageloader.ImageLoader;
import com.krain.corelibrary.http.depend.HttpRequest.HttpRequestException;
import com.orhanobut.logger.Logger;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.UiThread.Propagation;
import org.androidannotations.annotations.ViewById;
import org.apache.http.client.ClientProtocolException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.activity_mul_album)
public class MultipleAlbumActivity extends BaseActivity {
    private MultipleAlbumAdpter multipleAlbumAdpter;
    private int maxSelect = -1;
    @ViewById(R.id.multiple_gv)
    GridView                    gridView;
    public static final int     DEFAULT_HEIGHT   = 800;
    public static final int     DEFAULT_WIDTH    = 480;
    public static final int     COMPRESS_QAUILTY = 80;
    public static final String MAX_SELECTED_NUM_KEY = "max_selected_num_key";

    private static final String SUFFIX_JPG = ".jpg";
    private static final String SUFFIX_PNG = ".png";
    private File[] files ;
    private List<File> lists = new ArrayList<>();

    @Override
    protected String getToolbarTitle() {
        return null;
    }

    public static void jumpToThisActivityForResult(BaseActivity baseActivity, int requestCode, int maxSelectedNum) {
        Intent intent = new Intent(baseActivity, com.krain.ddbb.activity.MultipleAlbumActivity_.class);
        intent.putExtra(MAX_SELECTED_NUM_KEY, maxSelectedNum);
        baseActivity.startActivityForResultOnAnimation(baseActivity, intent, requestCode);
    }

    @Click(R.id.mul_album_complete)
    void complete() { // 完成
        compressing();
    }

    @ViewById(R.id.page_label_tv)
    TextView tvPageLabel; // titleBar 标题
    @ViewById(R.id.back_tv)
    TextView mTvBack;    // 返回

    @Click(R.id.back_tv)
    void Back() {
        setResult(RESULT_CANCELED);
        finish();
    }

    private ImageLoader mImageLoader;

    @Override
    public void baseAfterViews() {
        super.baseAfterViews();
        init();
    }

    void init() {
        //IconfontUtil.setIcon(this, mTvBack, "#
        mTvBack.setBackgroundResource(R.mipmap.ic_arrow_back);
        List<String> picUrls = getData();
        mImageLoader = ImageLoader.getInstance(this);
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            maxSelect = bundle.getInt(MAX_SELECTED_NUM_KEY, -1);
        }
        if(maxSelect < 0){
            tvPageLabel.setText("未选择");
        }else{
            tvPageLabel.setText("可选择"+maxSelect+"张");
        }
        
        if (picUrls != null) {
            multipleAlbumAdpter = new MultipleAlbumAdpter(picUrls, this, mImageLoader);
            gridView.setAdapter(multipleAlbumAdpter);
            gridView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                       int count = 0;
                       if(maxSelect == -1){//没张数限制
                           multipleAlbumAdpter.choiceState(position); 
                           count = multipleAlbumAdpter.getChooseNum();
                           if (count == 0) {
                               tvPageLabel.setText("未选择");
                           } else {
                               tvPageLabel.setText("已选择" + count + "张");
                           } 
                       }else{
                           if(!multipleAlbumAdpter.isChoosed(position)){
                               count = multipleAlbumAdpter.getChooseNum();
                               if(count < maxSelect){
                                   multipleAlbumAdpter.choiceState(position); 
                               }
                           }else{
                               multipleAlbumAdpter.choiceState(position); 
                           }
                           count = multipleAlbumAdpter.getChooseNum();
                           tvPageLabel.setText(count + "/"+maxSelect);
                       }
                }
            });
        }
    }

    /**
     * 压缩中
     */
    @Background(id = "compressing")
    void compressing() {
//        mImageLoader.clearMemoryCache();
        ArrayList<String> arrayList = multipleAlbumAdpter.getChoosePhtoto();
        String parentPath = TakePicByCameralActivity.getImageCheDir(this);
        ArrayList<String> filePaths = new ArrayList<String>();
        for (int i = 0; i < arrayList.size(); i++) {
            try {
                ImageHelper helper = ImageHelper.getInstance(this);
                Bitmap bitmap = helper.loadImage(arrayList.get(i), DEFAULT_WIDTH, DEFAULT_HEIGHT);

                if (bitmap != null) {
                    String path = parentPath + System.nanoTime() + ".jpg";
                    File file = new File(path);
                    File pf = file.getParentFile();
                    lists.add(new File(path));
                    uploadFile();
                    if (pf != null) {
                        pf.mkdirs();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    Logger.v("DaleLiu",path);

                    if (helper.writeToFile(bitmap, CompressFormat.JPEG, COMPRESS_QAUILTY, file)) {
                        filePaths.add(path);
                    }

                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (HttpRequestException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                Logger.v("DaleLiu", e.toString());
            }
        }
//        closeLoadingProgress();
        jumpBack(filePaths);
    }

    private void uploadFile() {
        files = new File[lists.size()];
        lists.toArray(files);

    }

    @UiThread(propagation = Propagation.REUSE)
    void jumpBack(ArrayList<String> filePaths) {
        Intent data = new Intent();
        data.putStringArrayListExtra(Keys.FILE_PATH_KEY, filePaths);
        setResult(RESULT_OK, data);
        finish();
    }

    /**
     * 获取相册文件夹下的文件
     * 
     * @return
     */
    private List<String> getData() {
        List<String> paths = new ArrayList<String>();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[] {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA};
        Cursor c = null;
        try {
            c = getContentResolver().query(uri, projection, null, null, null);
            if (c != null && c.moveToLast()) {
                do {
                    String path = c.getString(c.getColumnIndex(MediaStore.Images.Media.DATA));
                Logger.v("Eva", "path = " + path);
                    if (!TextUtils.isEmpty(path)) {
                        paths.add(path);
                    }
                } while (c.moveToPrevious());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return paths;
    }

    @Override
    protected void onDestroy() {
//        if (mImageLoader != null) {
////            mImageLoader.cancleTask();
////            mImageLoader.clearMemoryCache();
//            mImageLoader = null;
//        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        Back();
    }
}
